package com.lm.ProxyPattern;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK动态代理,实现java反射包中的InvocationHandler接口，重写invoke方法
 *  代理对象
 */
public class DynamicProxy implements InvocationHandler {

    //被代理的对象
    private Object target;

    public DynamicProxy(Object target){
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("请求前处理");
        Object result = method.invoke(target, args);
        System.out.println("请求后处理");
        return result;
    }

    public static void main(String[] args) {
        //需要被代理的对象
        RealSubject realSubject = new RealSubject();
        //代理对象
        DynamicProxy proxy = new DynamicProxy(realSubject);
        //生成代理类
        Subject instance = (Subject)Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), new Class[]{Subject.class}, proxy);
        instance.sayHello();
    }
}
